<?php
/**
 * Created by PhpStorm.
 * User: wzy12
 * Date: 2018/11/12
 * Time: 2:02
 */

namespace app\admin\model;


use think\Model;
use app\admin\validate\ReturnGoods as Vali;

class ReturnGoods extends Model
{
    /**
     * 退换货列表
     */
    public function resList($where){
        $query = $this -> where(1) -> alias('rg');

        // 筛选条件
        $is_where = $where;
        unset($is_where['page']);
        if($is_where) {
            if ($where) {
                // 查询退货类型
                if ($where['type'] || $where['type'] === '0') {
                    $query->where('type', $where['type']);
                }

                // 查询订单号
                if ($where['order_sn']) {
                    $query->where('order_sn', 'like', "%{$where['order_sn']}%");
                }
            }
        }

        $list = $query -> join('OrderGoods og', 'og.id = rg.res_id')
            -> field('rg.*,og.goods_name,og.spec_key_name')
            -> paginate(10, false, ['query'=>request()->param()]);

        return $list;
    }

    /**
     * 退换货操作
     */
    public function operation($data){
        // 验证
        $validate = new Vali();
        if(!$validate -> scene('form') -> check($data)){
            return echoArr(0, $validate->getError());
        }

        if($data['status'] == 1 || $data['status'] == -1){
            // 卖家审核时间
            $data['checktime'] = time();
        }else if($data['status'] == 3){
            // 卖家收货时间
            $data['receivetime'] = time();
        }else if($data['status'] == 4){
            // 用户发货信息
            $temp = ['express_name' => $data['express_name'], 'express_sn' => $data['express_sn'], 'express_time' => time()];

            $data['seller_delivery'] = serialize($temp);
        }

        $result = $this -> allowField(true) -> isUpdate(true) -> save($data);
        if(false === $result){
            return echoArr(1, '操作失败');
        }else{
            return echoArr(1, '操作成功');
        }
    }

    /**
     * 查询单条数据
     */
    public function resFind($id){
        $res = $this -> alias('rg')
            -> join('OrderGoods og', 'rg.res_id = og.id')
            -> join('Users u', 'u.id = rg.user_id')
            -> field('rg.*,og.goods_name,og.spec_key_name,u.username')
            -> find($id);

        // 用户收货信息
        if($res['delivery']){
            $res['delivery'] = unserialize($res['delivery']);
        }

        // 卖家发货信息
        if($res['seller_delivery']){
            $res['seller_delivery'] = unserialize($res['seller_delivery']);
        }

        return $res;
    }

    /**
     * 删除
     */
    public function del($data){
        // 验证
        $validate = new Vali();
        if(!$validate -> scene('del') -> check($data)){
            return echoArr(0, $validate->getError());
        }

        $result = $this -> destroy($data['id']);

        if(false === $result){
            return echoArr(0, '操作失败');
        }else{
            return echoArr(1, '操作成功');
        }
    }
}